package com.shuo.mmap;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用Mmap来读写文件
 * <p>
 * RocketMq.MappedFile#appendMessageInner
 */
public class MmapTest {

    public static void main(String[] args) {
        new MmapTest().writeInts();
    }

    /**
     * 将100000个连续数写入文件中
     */
    private void writeInts() {
        RandomAccessFile memoryMappedFile;
        int size = 1024 * 1024;
        try {
            memoryMappedFile = new RandomAccessFile("testMmap.txt", "rw");
            MappedByteBuffer mappedByteBuffer = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, size);
            for (int i = 0; i < 100000; i++) {
                mappedByteBuffer.position(i * 4);
                mappedByteBuffer.putInt(i);
            }
            memoryMappedFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
